﻿#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#include "crypt_des.h"

/*******************************************************************************
* @brief  encrypt
* \param[in] none
* \retval: none
*******************************************************************************/
void encrypt(void *src, int len, const void *key_src, int edflag)
{
	int i;
	uint32_t b[2];	
	struct expanded_key *key;
	char *block = src;
	
	struct expanded_key *des_key = malloc(sizeof(struct expanded_key));
	struct expanded_key *swap_key = malloc(sizeof(struct expanded_key));
	
	__des_setkey(key_src, des_key);
	
	// KEY 字节序变换
	key = des_key;
	if (edflag) {
		key = swap_key;
		for (i = 0; i < 16; i++) 
		{
			swap_key->l[i] = des_key->l[15-i];
			swap_key->r[i] = des_key->r[15-i];
		}
	}
	
	while( len > 0)
	{
		memcpy(b, block, 8);
		// 执行加密
		__do_des(b[0], b[1], b, b + 1, 1, 0, key);

		memcpy(block, b, 8);
		
		len -= 8;
		block += 8;
	}
	
	free(des_key);
	free(swap_key);
}
